package com.huluobo.a2207douyindemo.live;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2207douyindemo.R;
import com.huluobo.a2207douyindemo.adapter.ChatRoomAdapter;
import com.huluobo.a2207douyindemo.adapter.GiftAdapter;
import com.huluobo.a2207douyindemo.databinding.ActivityLiveBinding;
import com.huluobo.a2207douyindemo.pay.PayActivity;
import com.huluobo.a2207douyindemo.shop.ShopActivity;
import com.huluobo.a2207douyindemo.utils.ImageUtils;
import com.huluobo.base.bean.GiftBeanResult;
import com.huluobo.base.bean.Money;
import com.huluobo.base.bean.VideoBeanResult;
import com.huluobo.base.db.AppDBUtils;
import com.huluobo.base.mvvm.BaseMVVMActivity;
import com.huluobo.base.net.Const;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.List;

import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;


public class LiveActivity extends BaseMVVMActivity<ActivityLiveBinding, LiveViewModel> {
    private VideoBeanResult.VideoBean videoBean;
    private GiftAdapter giftAdapter;

    private GiftBeanResult.GiftBean giftBean;
    private Money money;
    private ChatRoomAdapter chatRoomAdapter;

    @Override
    protected void initData() {
        vm.followAuthSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(1);
                binding.liveFollowBtn.setText("已关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_black);
            }
        });

        vm.followAuthFailed.observe(this, s -> {
            Log.i("TagA", "关注失败:" + s);
        });

        vm.cancelFollowSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
            if (commonBeanResult.getCode() == 200) {
                videoBean.setGuanzhu(0);
                binding.liveFollowBtn.setText("关注");
                binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red);
            }
        });

        vm.cancelFollowFailed.observe(this, s -> {
            Log.i("TagA", "取消关注失败:" + s);
        });

        vm.getGiftSuccess.observe(this, giftBeanResult -> {
            if (giftBeanResult.getCode() == 200) {
                giftAdapter.getData().clear();
                giftAdapter.getData().addAll(giftBeanResult.getData());
                giftAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(giftBeanResult.getMessage());
            }
        });

        vm.getGiftFailed.observe(this, s -> {
            Log.i("TagA", "获取礼物列表失败:" + s);
        });
    }

    @Override
    protected void initView() {
        videoBean = (VideoBeanResult.VideoBean) getIntent().getSerializableExtra("videoBean");
        binding.liveGsyPlayer.getBackButton().setVisibility(View.GONE);
        binding.liveGsyPlayer.setUp(videoBean.getVideopath(), true, "");
//        binding.liveGsyPlayer.startPlayLogic();

        //头像
        ImageUtils.getInstance().loadCircleImage(this, videoBean.getHeadpath(), binding.liveUserIconIv);
        //作者名
        binding.liveUsernameTv.setText(videoBean.getAuthname());
        //关注状态
        binding.liveFollowBtn.setText(videoBean.getGuanzhu() == 0 ? "关注" : "已关注");
        binding.liveFollowBtn.setBackgroundResource(videoBean.getGuanzhu() == 0 ? R.drawable.shape_red :
                R.drawable.shape_black);
        //喜欢数量
        binding.liveLikeCountTv.setText(videoBean.getLike_count() + "人喜欢");
        //关注按钮的点击事件
        binding.liveFollowBtn.setOnClickListener(v -> {
            if (videoBean.getGuanzhu() == 0) {
                //未关注,触发关注接口
                vm.followAuth(videoBean.getAuthname());
            } else {
                //已关注,触发取消关注接口
                vm.cancelFollow(videoBean.getAuthname());
            }
        });

        //添加点赞动画的图片资源
        binding.liveLikeView.setIds(
                new int[]{
                        R.drawable.fav_0,
                        R.drawable.fav_1,
                        R.drawable.fav_2,
                        R.drawable.fav_3,
                        R.drawable.fav_4,
                        R.drawable.fav_5
                }
        );

        binding.liveLikeIv.setOnClickListener(v -> {
            binding.liveLikeView.addFavor();
        });

        //发送弹幕相关
        binding.liveDanmuIv.setOnClickListener(v -> {
            binding.liveDanmuLayoutLl.setVisibility(View.VISIBLE);
        });

        //初始化弹幕
//        initDanmu();

        //发送弹幕
        binding.liveDanmuSendIv.setOnClickListener(v -> {
//            sendDanmu();
            sendEasyDanmu();
        });

        //打开礼物列表
        binding.liveGiftIv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.VISIBLE);
            vm.getGift();
        });

        //关闭礼物列表
        binding.liveCloseTv.setOnClickListener(v -> {
            binding.liveGiftLayoutCl.setVisibility(View.GONE);
        });

        binding.liveGiftRv.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter();
        binding.liveGiftRv.setAdapter(giftAdapter);

        giftAdapter.setOnItemClickListener((adapter, view, position) -> {
            giftBean = giftAdapter.getData().get(position);
            ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), binding.liveGiftSelectIv);
            binding.liveGiftSelectTv.setText(giftBean.getGiftname());
        });

        binding.liveGiftSendBtn.setOnClickListener(v -> {
            sendGift();
        });

        binding.livePayBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, PayActivity.class);
            startActivity(intent);
        });

        binding.liveChatTv.setOnClickListener(v -> {
            binding.liveChatLl.setVisibility(View.VISIBLE);
        });

        //聊天室效果
        binding.liveChatSendIv.setOnClickListener(v -> {
//            //拿到聊天输入框的内容
            String msg = binding.liveChatEt.getText().toString();
            if (msg.isEmpty()) {
                ToastUtils.showLong("请输入聊天内容");
                return;
            }
//            String username = SPUtils.getInstance().getString(Const.PARAM_USERNAME);
//            MessageEntity message = new MessageEntity(username, msg);
//            chatRoomAdapter.getData().add(message);
//            chatRoomAdapter.notifyDataSetChanged();
//
//            binding.liveChatRv.scrollToPosition(chatRoomAdapter.getData().size() - 1);
//            binding.liveChatEt.setText("");
//            binding.liveChatLl.setVisibility(View.GONE);
            //发送聊天室消息
            sendEMMessage(Const.ROOM_ID, msg);
        });

        //聊天室rv初始化
        binding.liveChatRv.setLayoutManager(new LinearLayoutManager(this));
        chatRoomAdapter = new ChatRoomAdapter();
        binding.liveChatRv.setAdapter(chatRoomAdapter);

        //初始化聊天室功能
        initChatRoom();

        //跳转小黄车
        binding.liveCartIv.setOnClickListener(v -> {
            Intent intent = new Intent(this, ShopActivity.class);
            startActivity(intent);
        });
    }

    private void sendEMMessage(String roomId, String msg) {
        EMMessage message = EMMessage.createTextSendMessage(msg, roomId);
        message.setChatType(EMMessage.ChatType.GroupChat);//发送消息的类型,有3种,单聊,群聊,聊天室
        EMClient.getInstance().chatManager().sendMessage(message);//发送消息到服务器
        //设置消息监听器
        message.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    MessageEntity messageEntity = new MessageEntity(
                            EMClient.getInstance().getCurrentUser(),
//                        SPUtils.getInstance().getString(Const.PARAM_USERNAME),//可以从sp中获取当前用户,也可以从EMClient中获取用户
                            msg
                    );
                    chatRoomAdapter.getData().add(messageEntity);//将消息对象放到adapter中
                    chatRoomAdapter.notifyDataSetChanged();
                    binding.liveChatRv.scrollToPosition(chatRoomAdapter.getData().size() - 1);
                    binding.liveChatEt.setText("");
                    binding.liveChatLl.setVisibility(View.GONE);
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.i("TagA", "发送聊天室消息失败:" + error + ",code:" + code);
            }
        });
    }

    private void initChatRoom() {
        //添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        //添加聊天室监听器
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
        //进入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.ROOM_ID, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                Log.i("TagA", "加入聊天室成功");
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA", "加入聊天室失败:" + errorMsg + ",code:" + error);
            }
        });
    }

    //接受消息监听器,主要监听新消息
    private EMMessageListener messageListener = messages -> {
        //也需要切换线程
        runOnUiThread(() -> {
            for (int i = 0; i < messages.size(); i++) {
                MessageEntity messageEntity = new MessageEntity(
                        messages.get(i).getUserName(),
                        ((EMTextMessageBody) messages.get(i).getBody()).getMessage()
                );
                chatRoomAdapter.getData().add(messageEntity);
                chatRoomAdapter.notifyDataSetChanged();
            }
        });
    };

    //聊天室状态改变监听器,主要监听成员进入和退出
    private EMChatRoomChangeListener chatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            runOnUiThread(() -> {
                MessageEntity messageEntity = new MessageEntity(
                        "系统",
                        participant + "加入直播间"
                );
                chatRoomAdapter.getData().add(messageEntity);
                chatRoomAdapter.notifyDataSetChanged();
            });
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {
            runOnUiThread(() -> {
                MessageEntity messageEntity = new MessageEntity(
                        "系统",
                        participant + "退出直播间"
                );
                chatRoomAdapter.getData().add(messageEntity);
                chatRoomAdapter.notifyDataSetChanged();
            });
        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出聊天室
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.ROOM_ID);
        //移除消息监听器
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        //移除聊天室监听器
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        money =
                AppDBUtils.getInstance().getMoneyDao().queryUserMoneyByName(SPUtils.getInstance().getString(Const.PARAM_USERNAME));

        binding.liveUserMoneyTv.setText("余额:" + money.getMoney() + "抖币");
    }

    //发送礼物
    private void sendGift() {
        //拿到用户余额(查询money,并赋值)
        //扣款(检查用户余额是否充足,充足 余额扣款,不充足,提示充值)
        //扣款-> 更新UI,更新数据中保存新的余额
        if (giftBean == null || money == null) {
            ToastUtils.showLong("请选择礼物,或者查询余额失败");
            return;
        }

        //判断余额是否充足
        if (money.getMoney() < giftBean.getPrice()) {
            ToastUtils.showLong("余额不足,请充值");
            return;
        }

        float newMoney = money.getMoney() - giftBean.getPrice();
        binding.liveUserMoneyTv.setText("余额:" + newMoney + "抖币");
        //money不能new,如果new过之后,会产生新的id,就是另一个money了,和之前获取的money不是一个对象
        money.setMoney(newMoney);
        //更新之后,保存到数据库
        AppDBUtils.getInstance().getMoneyDao().updateMoney(money);

        //构建一个ImageView,承载礼物动画
        ImageView giftView = new ImageView(this);
        //直接newView,没有属性,也没有宽高,都需要设置一个宽高才能显示
        //宽高无法直接给view去set,需要通过一个LayoutParams来设置
        //这个View需要展示在哪个layout上,就是用哪个layout的params
        ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(200, 200);
        giftView.setLayoutParams(params);

        //通过最大layout动态添加一个view
        binding.liveRootCl.addView(giftView);
        //给imageView添加图片资源
        ImageUtils.getInstance().loadImage(this, giftBean.getGiftpath(), giftView);

        //展示礼物动画
        //获取最大layout的宽高
        float screenWidth = (float) binding.liveRootCl.getMeasuredWidth();
        float screenHeight = (float) binding.liveRootCl.getMeasuredHeight();

        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftView, "translationX", screenWidth / 2,
                screenWidth / 3, screenWidth / 2, screenWidth / 3 * 2, screenWidth / 2, screenWidth / 5 * 2);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftView, "translationY", screenHeight, screenHeight / 2
                , screenHeight / 5, screenHeight / 3, screenHeight / 2, screenHeight / 5 * 2);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftView, "rotation", 0, 1800);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftView, "scaleX", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftView, "scaleY", 1, 2, 1, 3, 1, 2, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftView, "alpha", 1, 0);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(3000);
        set.playTogether(translationY, translationX, rotation, scaleX, scaleY, alpha);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //动画开始时,关闭礼物布局
                binding.liveGiftLayoutCl.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //动画结束时,隐藏礼物view
                binding.liveRootCl.removeView(giftView);
            }
        });
        set.start();
    }

    private void sendEasyDanmu() {
        //获取弹幕内容
        String danmuString = binding.liveDanmuEt.getText().toString();
        if (danmuString.isEmpty()) {
            ToastUtils.showLong("弹幕内容不能为空");
            return;
        }

        //设置简单弹幕
        Danmaku danmaku = new Danmaku();
        danmaku.text = danmuString;
        danmaku.size = 30;
        DanmakuManager.getInstance().init(this, binding.liveDanmuView);
        DanmakuManager.getInstance().send(danmaku);

        //发送弹幕之后清空弹幕输入框,隐藏弹幕布局
        binding.liveDanmuEt.setText("");
        binding.liveDanmuLayoutLl.setVisibility(View.GONE);
    }
//
//    private void sendDanmu() {
//        //获取弹幕内容
//        String danmuString = binding.liveDanmuEt.getText().toString();
//        if (danmuString.isEmpty()) {
//            ToastUtils.showLong("弹幕内容不能为空");
//            return;
//        }
//
//        //清理弹幕
//        binding.liveDanmuView.clear();
//        binding.liveDanmuView.removeAllDanmakus(true);
//
//        //创建一条弹幕
//        BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
//        danmaku.text = danmuString;//弹幕文本
//        danmaku.textSize = 30;
//        danmaku.textColor = Color.WHITE;
//        danmaku.setTime(800);
//
//        //添加弹幕到弹幕View中
//        binding.liveDanmuView.addDanmaku(danmaku);
//        binding.liveDanmuView.start();//启动弹幕
//
//        //发送弹幕之后清空弹幕输入框,隐藏弹幕布局
//        binding.liveDanmuEt.setText("");
//        binding.liveDanmuLayoutLl.setVisibility(View.GONE);
//    }
//
//    private DanmakuContext danmakuContext;
//
//    private void initDanmu() {
//        //1.清理弹幕缓存
//        binding.liveDanmuView.enableDanmakuDrawingCache(false);
//        //清空弹幕view
//        binding.liveDanmuView.clear();
//        //移除所有弹幕
//        binding.liveDanmuView.removeAllDanmakus(true);
//
//        //2.创建弹幕上下文
//        danmakuContext = DanmakuContext.create();
//
//        //3.准备弹幕
//        binding.liveDanmuView.prepare(new BaseDanmakuParser() {
//            @Override
//            protected IDanmakus parse() {
//                return new Danmakus();
//            }
//        }, danmakuContext);
//    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }
}